import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	login,
	logout,
	getInfo
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'
import defaultAvatar from '@/static/images/profile.jpg'
const baseUrl = config.baseUrl
const useUserStore = defineStore('user', {
	state: () => ({
		token: getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		roles: storage.get(constant.roles),
		permissions: storage.get(constant.permissions),
		loginType: 1,
		userInfo: '',
		userId: 0,
		authSource: '',
		userName: '',
		base: '',
		baseName: '',
		factory: '',
		clientId: ''
	}),
	actions: {
		// 登录
		Login( userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			return new Promise((resolve, reject) => {
				login(username, password, code, uuid).then(res => {
					setToken(res.data)
					this.token = res.data
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetInfo() {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.data.user
					const data = res.data
					const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
						defaultAvatar :user.avatar
					const username = (user == null || user.userName == "" || user.userName ==
						null) ? "" : user.userName
					if (data.roles && data.roles.length > 0) {
						// 验证返回的roles是否是一个非空数组
						this.roles = data.roles
						this.permissions = data.permissions
					} else {
						this.roles = ['ROLE_DEFAULT']
					}
					this.name = data.user.nickName
					this.avatar = import.meta.env.VITE_APP_ATTACHMENTS_API+avatar
					this.userInfo = data.user //新加
					this.userId = data.user.userId //新加
					this.userName = data.user.userName //新加
					this.base = data.user.base //新加
					this.baseName = data.user.baseName //新加
					this.factory = data.user.factory //新加
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut() {
			return new Promise((resolve, reject) => {
				logout(this.token).then(() => {
					this.token = ''
					this.roles = []
					this.permissions = []
					removeToken()
					storage.clean()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
});

export default useUserStore